﻿/************************************************************************

   Extended Silverlight Toolkit

   Copyright (C) 2010-2012 Xceed Software Inc.

   This program is provided to you under the terms of the Microsoft Public
   License (Ms-PL) as published at http://extendedsilverlight.codeplex.com/license

   Please purchase a commercial version of this toolkit if you are using
   it in a commercial product. The commercial versions support the project,
   and also include more features for each control, priority support,
   source code, updates, removed watermark, and a proprietary license.

   Visit http://xceed.com and follow @datagrid on Twitter.

  **********************************************************************/

using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Xceed.Silverlight.Utils;

namespace Xceed.Silverlight.Controls
{
  [TemplateVisualState( GroupName = "CommonStates", Name = "Disabled" )]
  [TemplateVisualState( GroupName = "CommonStates", Name = "Normal" )]
  [TemplateVisualState( GroupName = "CommonStates", Name = "MouseOver" )]
  [TemplateVisualState( GroupName = "FocusStates", Name = "Unfocused" )]
  [TemplateVisualState( GroupName = "FocusStates", Name = "Focused" )]
  public class DataNavigationItem : Control
  {
    #region Constructors

    public DataNavigationItem()
    {
      this.DefaultStyleKey = typeof( DataNavigationItem );
      this.Loaded += this.OnLoaded;
      this.Unloaded += this.OnUnloaded;
      this.IsEnabledChanged += this.OnIsEnabledChanged;
    }

    #endregion

    #region Click Public Event

    public event MouseButtonEventHandler Click;

    #endregion

    #region Command Property

    public static readonly DependencyProperty CommandProperty = DependencyProperty.Register(
      "Command",
      typeof( ICommand ),
      typeof( DataNavigationItem ),
      new PropertyMetadata( null ) );

    public ICommand Command
    {
      get
      {
        return ( ICommand )this.GetValue( DataNavigationItem.CommandProperty );
      }
      set
      {
        this.SetValue( DataNavigationItem.CommandProperty, value );
      }
    }

    #endregion

    #region CommandParameter Property

    public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register(
      "CommandParameter",
      typeof( object ),
      typeof( DataNavigationItem ),
      new PropertyMetadata( null ) );

    public object CommandParameter
    {
      get
      {
        return ( object )this.GetValue( DataNavigationItem.CommandParameterProperty );
      }
      set
      {
        this.SetValue( DataNavigationItem.CommandParameterProperty, value );
      }
    }

    #endregion

    #region ContentTemplate Property

    public static readonly DependencyProperty ContentTemplateProperty = DependencyProperty.Register(
      "ContentTemplate",
      typeof( DataTemplate ),
      typeof( DataNavigationItem ),
      new PropertyMetadata( null ) );

    public DataTemplate ContentTemplate
    {
      get
      {
        return ( DataTemplate )this.GetValue( DataNavigationItem.ContentTemplateProperty );
      }
      set
      {
        this.SetValue( DataNavigationItem.ContentTemplateProperty, value );
      }
    }

    #endregion

    #region IsFocused Internal Property

    internal bool IsFocused
    {
      get
      {
        return m_isFocused;
      }
      set
      {
        if( m_isFocused != value )
        {
          m_isFocused = value;
          this.ChangeVisualState();
        }
      }
    }

    private bool m_isFocused;

    #endregion

    #region IsMouseOver Internal Property

    internal bool IsMouseOver
    {
      get
      {
        return m_isMouseOver;
      }
      set
      {
        if( m_isMouseOver != value )
        {
          m_isMouseOver = value;
          this.ChangeVisualState();
        }
      }
    }

    private bool m_isMouseOver;

    #endregion

    #region IsMouseCaptured Private Property

    private bool IsMouseCaptured
    {
      get
      {
        return m_isMouseCaptured;
      }
      set
      {
        if( m_isMouseCaptured != value )
        {
          m_isMouseCaptured = value;
        }
      }
    }

    private bool m_isMouseCaptured;

    #endregion

    #region IsPressed Private Property

    private bool IsPressed
    {
      get
      {
        return m_isPressed;
      }
      set
      {
        if( m_isPressed != value )
        {
          m_isPressed = value;
        }
      }
    }

    private bool m_isPressed;

    #endregion

    #region Internal Methods

    internal void ChangeVisualState()
    {
      this.ChangeVisualState( true );
    }

    internal bool GoToState( bool useTransitions, string stateName )
    {
      return VisualStateManager.GoToState( this, stateName, useTransitions );
    }

    #endregion

    #region Protected Methods

    protected internal virtual void ChangeVisualState( bool useTransitions )
    {
      this.UpdateCommonStates( useTransitions );
      this.UpdateFocusStates( useTransitions );
    }

    protected virtual void OnClick( MouseButtonEventArgs e )
    {
      if( this.Click != null )
      {
        this.Click( this, e );
      }

      this.ExecuteCommand();
    }

    protected virtual void ExecuteCommand()
    {
      ICommand command = this.Command;

      if( command == null )
        return;

      object parameter = this.CommandParameter;

      if( command.CanExecute( parameter ) )
      {
        command.Execute( parameter );
      }
    }

    protected virtual void OnLoaded()
    {
    }

    protected virtual void OnUnloaded()
    {
    }

    protected virtual void OnIsEnabledChanged( object sender, DependencyPropertyChangedEventArgs e )
    {
      this.ChangeVisualState();
    }

    protected override void OnGotFocus( RoutedEventArgs e )
    {
      base.OnGotFocus( e );
      this.IsFocused = FocusHelper.HasFocus( this );
    }

    protected override void OnLostFocus( RoutedEventArgs e )
    {
      base.OnLostFocus( e );
      this.IsFocused = FocusHelper.HasFocus( this );
    }

    protected override void OnMouseEnter( MouseEventArgs e )
    {
      base.OnMouseEnter( e );
      this.IsMouseOver = true;
    }

    protected override void OnMouseLeave( MouseEventArgs e )
    {
      base.OnMouseLeave( e );
      this.IsMouseOver = false;
    }

    protected override void OnMouseLeftButtonDown( MouseButtonEventArgs e )
    {
      base.OnMouseLeftButtonDown( e );

      if( !e.Handled )
      {
        if( this.IsEnabled )
        {
          e.Handled = true;

          try
          {
            this.CaptureMouseInternal();
          }
          finally
          {
          }

          this.IsPressed = this.IsMouseCaptured;
        }
        else
        {
          this.IsPressed = false;
        }
      }
    }

    protected override void OnMouseLeftButtonUp( MouseButtonEventArgs e )
    {
      base.OnMouseLeftButtonUp( e );

      if( !e.Handled )
      {
        bool isClicked = this.IsPressed;

        try
        {
          this.ReleaseMouseCaptureInternal();
        }
        finally
        {
          this.IsPressed = false;
        }

        if( this.IsEnabled )
        {
          e.Handled = true;

          if( isClicked )
          {
            this.OnClick( e );
          }
        }
      }
    }

    protected override void OnMouseMove( MouseEventArgs e )
    {
      base.OnMouseMove( e );

      if( this.IsMouseCaptured && this.IsEnabled )
      {
        this.IsPressed = this.IsValidMousePosition( e.GetPosition( this ) );
      }
    }

    #endregion

    #region Private Methods

    private void OnLoaded( object sender, RoutedEventArgs e )
    {
      this.ChangeVisualState( false );
      this.OnLoaded();
    }

    private void OnUnloaded( object sender, RoutedEventArgs e )
    {
      this.ChangeVisualState( false );
      this.OnUnloaded();
    }

    private void UpdateCommonStates( bool useTransitions )
    {
      if( !base.IsEnabled )
      {
        this.GoToState( useTransitions, "Disabled" );
      }
      else if( this.IsMouseOver )
      {
        this.GoToState( useTransitions, "MouseOver" );
      }
      else
      {
        this.GoToState( useTransitions, "Normal" );
      }
    }

    private void UpdateFocusStates( bool useTransitions )
    {
      if( this.IsFocused )
      {
        this.GoToState( useTransitions, "Focused" );
      }
      else
      {
        this.GoToState( useTransitions, "Unfocused" );
      }
    }

    private void CaptureMouseInternal()
    {
      if( !this.IsMouseCaptured )
      {
        this.IsMouseCaptured = this.CaptureMouse();
      }
    }

    private void ReleaseMouseCaptureInternal()
    {
      this.ReleaseMouseCapture();

      this.IsMouseCaptured = false;
    }

    private bool IsValidMousePosition( Point pos )
    {
      return ( ( ( ( pos.X >= 0.0 ) && ( pos.X <= this.ActualWidth ) ) && ( pos.Y >= 0.0 ) ) && ( pos.Y <= this.ActualHeight ) );
    }

    #endregion
  }
}
